<template>
  <div>
    <!-- nav -->
    <van-nav-bar class="my-nav-bar" title="登录" />
    <!-- 输入框  pattern-->
    <van-form @submit="onSubmit">
      <van-field
        required
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入正确的手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不正确'
          }
        ]"
      />
      <van-field
        required
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请输入正确的验证码' },
          { pattern: /\d{6}/, message: '验证码格式不正确' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isDisabled"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入 api方法
import { userLogin } from '../../api/login.js'
// 导入token
import { saveToken } from '../../utils/token.js'
export default {
  data () {
    return {
      mobile: '',
      code: '246810',
      isLoading: false,
      isDisabled: false
    }
  },
  methods: {
    onSubmit (values) {
      console.log('submit', values)
      this.isLoading = true
      // this.isDisabled = true
      userLogin(values)
        .then(res => {
          console.log(res)
          this.$toast.success('登陆成功！')
          this.isLoading = false
          // this.isDisabled = false
          saveToken(res.data.data)
          // 跳转home
          if (this.$route.query.back) {
            this.$router.push({
              path: this.$route.query.back
            })
          } else {
            this.$router.push({
              path: '/home'
            })
          }
        })
        .catch(res => {
          console.log(res)
          this.$toast.fail('登陆失败！')
          this.isLoading = false
          // this.isDisabled = false
        })
    }
  }
}
</script>

<style lang="less">
.my-nav-bar.van-nav-bar {
  background-color: #1989fa;
  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
